using System;
using System.Threading.Tasks;

namespace LiJ.Common.Plugs.LogPlug
{
	/// <summary>
	/// 日志写模块
	/// </summary>
	public static class LogUtil
	{
		private static readonly DefaultLogPlug DefaultCache = new DefaultLogPlug();

		/// <summary>
		/// 通过模块名称获取日志模块实例
		/// </summary>
		/// <param name="logModule"></param>
		/// <returns></returns>
		public static ILogPlug GetLogWrite(string logModule)
		{
			if (string.IsNullOrEmpty(logModule))
			{
				logModule = "default";
			}
			Func<string, ILogPlug> logWriterProvider = OsConfig.LogWriterProvider;
			return logWriterProvider?.Invoke(logModule) ?? DefaultCache;
		}

		/// <summary>
		/// 记录信息
		/// </summary>
		/// <param name="msg"> 日志信息  </param>
		/// <param name="msgKey">  关键值  </param>
		/// <param name="moduleName"> 模块名称 </param>
		public static string Info(object msg, string msgKey = null, string moduleName = "default")
		{
			return Log(new LogInfo(LogLevelEnum.Info, msg, msgKey, moduleName));
		}

		/// <summary>
		/// 记录警告，用于未处理异常的捕获
		/// </summary>
		/// <param name="msg"> 日志信息  </param>
		/// <param name="msgKey">  关键值  </param>
		/// <param name="moduleName">模块名称</param>
		public static string Warning(object msg, string msgKey = null, string moduleName = "default")
		{
			return Log(new LogInfo(LogLevelEnum.Warning, msg, msgKey, moduleName));
		}

		/// <summary>
		/// 记录错误，用于捕获到的异常信息记录
		/// </summary>
		/// <param name="msg"> 日志信息  </param>
		/// <param name="msgKey">  关键值  </param>
		/// <param name="moduleName">模块名称</param>
		public static string Error(object msg, string msgKey = null, string moduleName = "default")
		{
			return Log(new LogInfo(LogLevelEnum.Error, msg, msgKey, moduleName));
		}

		/// <summary>
		/// 记录错误，用于捕获到的异常信息记录
		/// </summary>
		/// <param name="msg"> 日志信息  </param>
		/// <param name="msgKey">  关键值  </param>
		/// <param name="moduleName">模块名称</param>
		public static string Trace(object msg, string msgKey = null, string moduleName = "default")
		{
			return Log(new LogInfo(LogLevelEnum.Trace, msg, msgKey, moduleName));
		}

		/// <summary>
		///   记录日志
		/// </summary>
		/// <param name="info"></param>
		private static string Log(LogInfo info)
		{
			if (string.IsNullOrEmpty(info.ModuleName))
			{
				info.ModuleName = "default";
			}
			ILogPlug logWrite = GetLogWrite(info.ModuleName);
			logWrite.SetLogCode(info);
			Task.Run(delegate
			{
				logWrite.WriteLog(info);
			});
			return info.LogCode;
		}
	}
}
